<template>
  <div class="container mx-auto px-4 py-8">
    <!-- 返回按钮 -->
    <el-button 
      class="mb-6" 
      @click="router.back()"
      :icon="ArrowLeft"
    >
      返回
    </el-button>

    <!-- 主要内容 -->
    <div v-loading="loading" class="grid grid-cols-1 lg:grid-cols-3 gap-8">
      <!-- 左侧主要内容 -->
      <div class="lg:col-span-2 space-y-6">
        <!-- 文章卡片 -->
        <el-card v-if="share" class="post-detail-card">
          <!-- 作者信息 -->
          <div class="flex items-center justify-between mb-6">
            <div class="flex items-center gap-4">
              <el-avatar 
                :size="56" 
                :src="getUserAvatar(share)"
                @click="navigateToUserProfile(share.userId)"
                class="cursor-pointer hover:ring-2 hover:ring-blue-500 transition-all duration-300"
              />
              <div>
                <div 
                  class="text-lg font-semibold hover:text-blue-600 cursor-pointer"
                  @click="navigateToUserProfile(share.userId)"
                >
                  {{ share.createBy }}
                </div>
              </div>
            </div>
            <el-button v-if="isCurrentUser" type="danger" text @click="handleDelete">
              删除
            </el-button>
          </div>

          <!-- 文章内容 -->
          <div class="text-gray-500 text-sm mb-6 flex items-center gap-4">
            <span>{{ formatTime(share.createTime) }}</span>
            <span>浏览 {{ share.viewCount || 0 }}</span>
          </div>
          
          <div class="prose max-w-none mb-6">
            {{ share.content }}
          </div>

          <!-- 标签 -->
          <div class="flex flex-wrap gap-2 mb-6">
            <el-tag
              v-for="tagId in share.tagsId"
              :key="tagId"
              effect="plain"
              class="cursor-pointer hover:scale-105 transition-transform duration-300"
              @click="handleTagClick(tagId)"
            >
              {{ getTagName(tagId) }}
            </el-tag>
          </div>

          <!-- 互动栏 -->
          <div class="flex items-center gap-8 text-gray-500 border-t pt-6">
            <button 
              class="flex items-center gap-2 hover:text-blue-600 transition-colors duration-300"
            >
              <el-icon :size="24"><View /></el-icon>
              <span>{{ share.viewCount || 0 }} 浏览</span>
            </button>
            <button 
              class="flex items-center gap-2 hover:text-blue-600 transition-colors duration-300"
              @click="focusComment"
            >
              <el-icon :size="24"><ChatRound /></el-icon>
              <span>{{ share.commentCount || 0 }} 评论</span>
            </button>
          </div>
        </el-card>

        <!-- 评论区 -->
        <div class="bg-white rounded-lg shadow p-6">
          <h2 class="text-xl font-bold mb-6">评论 {{ comments.length }}</h2>
          
          <!-- 评论输入框 -->
          <div class="mb-8">
            <el-input
              ref="commentInputRef"
              v-model="commentContent"
              type="textarea"
              :rows="3"
              placeholder="写下你的评论..."
              maxlength="500"
              show-word-limit
            />
            <div class="flex justify-between items-center mt-2">
              <span class="text-gray-500 text-sm">还可输入 {{ 500 - commentContent.length }} 字</span>
              <el-button type="primary" @click="submitComment" :loading="submitting" :disabled="!commentContent.trim()">
                发表评论
              </el-button>
            </div>
          </div>

          <!-- 评论列表 -->
          <div v-loading="commentsLoading" class="space-y-6">
            <el-empty v-if="comments.length === 0" description="暂无评论，来发表第一条评论吧" />
            
            <div 
              v-for="comment in comments" 
              :key="comment.commentId"
              class="flex gap-4"
            >
              <el-avatar 
                :size="40" 
                :src="comment.commentAvatar || defaultAvatar"
                class="cursor-pointer flex-shrink-0"
              />
              <div class="flex-grow">
                <div class="flex items-center justify-between">
                  <div>
                    <span class="font-semibold">
                      {{ comment.commentUser }}
                    </span>
                  </div>
                  <span class="text-gray-500 text-sm">
                    {{ formatTime(comment.commentTime) }}
                  </span>
                </div>
                <p class="text-gray-700 mt-2">{{ comment.commentContent }}</p>
                <div class="flex items-center gap-4 mt-2 text-sm text-gray-500">
                  <button 
                    class="hover:text-blue-600 transition-colors duration-300"
                    @click="replyToComment(comment)"
                  >
                    回复
                  </button>
                  <button 
                    v-if="canDeleteComment(comment)"
                    class="hover:text-red-600 transition-colors duration-300"
                    @click="deleteCommentConfirm(comment.commentId)"
                  >
                    删除
                  </button>
                </div>

                <!-- 回复输入框 -->
                <div
                  v-if="activeReplyId === comment.commentId"
                  class="mt-4 bg-gray-50 p-4 rounded-lg"
                >
                  <el-input
                    v-model="replyContent"
                    type="textarea"
                    :rows="2"
                    :placeholder="`回复 ${comment.commentUser}`"
                    maxlength="500"
                    show-word-limit
                  />
                  <div class="flex justify-between items-center mt-2">
                    <span class="text-gray-500 text-sm">还可输入 {{ 500 - replyContent.length }} 字</span>
                    <div class="space-x-2">
                      <el-button @click="cancelReply">取消</el-button>
                      <el-button type="primary" @click="submitReply(comment.commentId)" :loading="replySubmitting" :disabled="!replyContent.trim()">
                        回复
                      </el-button>
                    </div>
                  </div>
                </div>

                <!-- 回复列表 -->
                <div v-if="comment.replies && comment.replies.length" class="mt-4 space-y-4 pl-4 border-l-2 border-gray-100">
                  <div 
                    v-for="reply in comment.replies" 
                    :key="reply.commentId"
                    class="flex gap-3"
                  >
                    <el-avatar 
                      :size="32" 
                      :src="reply.commentAvatar || defaultAvatar"
                      class="flex-shrink-0"
                    />
                    <div class="flex-grow">
                      <div class="flex items-center justify-between">
                        <div>
                          <span class="font-semibold">
                            {{ reply.commentUser }}
                          </span>
                          <span class="text-gray-500 text-sm ml-2">
                            回复 {{ reply.replyToName }}
                          </span>
                        </div>
                        <span class="text-gray-500 text-sm">
                          {{ formatTime(reply.commentTime) }}
                        </span>
                      </div>
                      <p class="text-gray-700 mt-1">{{ reply.commentContent }}</p>
                      <div class="flex items-center gap-4 mt-1 text-sm text-gray-500">
                        <button 
                          class="hover:text-blue-600 transition-colors duration-300"
                          @click="replyToComment(comment, reply.commentUser)"
                        >
                          回复
                        </button>
                        <button 
                          v-if="canDeleteComment(reply)"
                          class="hover:text-red-600 transition-colors duration-300"
                          @click="deleteCommentConfirm(reply.commentId)"
                        >
                          删除
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 分页 -->
            <el-pagination
              v-if="total > 0"
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="total"
              :page-sizes="[10, 20, 30, 50]"
              layout="total, sizes, prev, pager, next"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>

      <!-- 右侧相关推荐 -->
      <div class="space-y-6">
        <el-card class="relative">
          <template #header>
            <div class="font-semibold text-lg">热门标签</div>
          </template>
          <div class="flex flex-wrap gap-2">
            <el-tag
              v-for="tag in tagOptions"
              :key="tag.tagId"
              class="cursor-pointer hover:scale-105 transition-transform duration-300 my-1"
              @click="handleTagNavigate(tag.tagId)"
            >
              {{ tag.tagName }}
            </el-tag>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, View, ChatRound, Star } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'
import { 
  getShareDetail, 
  getAllTags, 
  deleteShare, 
  getTopComments,
  getReplyComments,
  addComment,
  deleteComment
} from '@/api/share'
import { useUserStore } from '@/store/user'

dayjs.extend(relativeTime)
dayjs.locale('zh-cn')

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 状态数据
const loading = ref(false)
const commentsLoading = ref(false)
const share = ref(null)
const shareId = computed(() => route.params.id || '')
const tagOptions = ref([])
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

// 评论状态
const commentContent = ref('')
const replyContent = ref('')
const activeReplyId = ref(null)
const replyToUser = ref(null)
const comments = ref([])
const submitting = ref(false)
const replySubmitting = ref(false)
const commentInputRef = ref(null)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 获取用户头像
const getUserAvatar = (share) => {
  // 可以根据实际情况获取用户头像，这里使用默认头像
  return defaultAvatar
}

// 获取标签名称
const getTagName = (tagId) => {
  const tag = tagOptions.value.find(t => t.tagId === tagId)
  return tag ? tag.tagName : tagId
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  return dayjs(time).fromNow()
}

// 是否为当前用户的分享
const isCurrentUser = computed(() => {
  return share.value && share.value.userId === userStore.userId
})

// 判断是否可以删除评论
const canDeleteComment = (comment) => {
  return comment.commentUser === userStore.username || isCurrentUser.value
}

// 获取分享详情
const fetchShareDetail = async () => {
  loading.value = true
  try {
    const res = await getShareDetail(shareId.value)
    if (res.code === 0 || res.code === 200) {
      share.value = res.data
    } else {
      ElMessage.error(res.message || '获取分享详情失败')
    }
  } catch (error) {
    console.error('获取分享详情失败:', error)
    ElMessage.error('获取分享详情失败')
  } finally {
    loading.value = false
  }
}

// 获取评论列表
const fetchComments = async () => {
  commentsLoading.value = true
  try {
    const res = await getTopComments({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      shareId: shareId.value
    })
    
    if (res.code === 0 || res.code === 200) {
      comments.value = res.data.records || []
      total.value = res.data.total || 0
      
      // 获取每个评论的回复
      if (comments.value.length > 0) {
        await Promise.all(
          comments.value.map(async (comment) => {
            try {
              const repliesRes = await getReplyComments({
                parentId: comment.commentId,
                topId: comment.commentId
              })
              
              if (repliesRes.code === 0 || repliesRes.code === 200) {
                comment.replies = repliesRes.data || []
              } else {
                comment.replies = []
              }
            } catch (error) {
              console.error('获取回复评论失败:', error)
              comment.replies = []
            }
          })
        )
      }
    } else {
      ElMessage.error(res.message || '获取评论列表失败')
    }
  } catch (error) {
    console.error('获取评论列表失败:', error)
    ElMessage.error('获取评论列表失败')
  } finally {
    commentsLoading.value = false
  }
}

// 获取标签列表
const fetchTags = async () => {
  try {
    const res = await getAllTags()
    if (res.code === 0 || res.code === 200) {
      tagOptions.value = res.data || []
    } else {
      console.error('获取标签列表失败:', res.message)
    }
  } catch (error) {
    console.error('获取标签列表失败:', error)
  }
}

// 提交评论
const submitComment = async () => {
  if (!userStore.token) {
    ElMessage.warning('请先登录')
    return
  }
  
  if (!commentContent.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }
  
  submitting.value = true
  try {
    const res = await addComment({
      shareId: shareId.value,
      content: commentContent.value
    })
    
    if (res.code === 0 || res.code === 200) {
      ElMessage.success('评论发表成功')
      commentContent.value = ''
      await fetchComments()
    } else {
      ElMessage.error(res.message || '评论发表失败')
    }
  } catch (error) {
    console.error('评论发表失败:', error)
    ElMessage.error('评论发表失败')
  } finally {
    submitting.value = false
  }
}

// 回复评论
const replyToComment = (comment, replyToUsername = null) => {
  if (!userStore.token) {
    ElMessage.warning('请先登录')
    return
  }
  
  activeReplyId.value = comment.commentId
  replyToUser.value = replyToUsername || comment.commentUser
  replyContent.value = ''
}

// 取消回复
const cancelReply = () => {
  activeReplyId.value = null
  replyToUser.value = null
  replyContent.value = ''
}

// 提交回复
const submitReply = async (parentId) => {
  if (!userStore.token) {
    ElMessage.warning('请先登录')
    return
  }
  
  if (!replyContent.value.trim()) {
    ElMessage.warning('请输入回复内容')
    return
  }
  
  replySubmitting.value = true
  try {
    const res = await addComment({
      shareId: shareId.value,
      parentId: parentId,
      content: replyContent.value
    })
    
    if (res.code === 0 || res.code === 200) {
      ElMessage.success('回复发表成功')
      cancelReply()
      await fetchComments()
    } else {
      ElMessage.error(res.message || '回复发表失败')
    }
  } catch (error) {
    console.error('回复发表失败:', error)
    ElMessage.error('回复发表失败')
  } finally {
    replySubmitting.value = false
  }
}

// 删除分享
const handleDelete = async () => {
  try {
    await ElMessageBox.confirm('确定要删除这条分享吗？删除后无法恢复', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteShare(shareId.value)
    
    if (res.code === 0 || res.code === 200) {
      ElMessage.success('删除成功')
      router.push('/share')
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 删除评论
const deleteCommentConfirm = async (commentId) => {
  try {
    await ElMessageBox.confirm('确定要删除这条评论吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteComment(commentId)
    
    if (res.code === 0 || res.code === 200) {
      ElMessage.success('删除成功')
      await fetchComments()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 聚焦评论输入框
const focusComment = () => {
  if (commentInputRef.value) {
    commentInputRef.value.focus()
  }
}

// 标签点击
const handleTagClick = (tagId) => {
  router.push(`/share?tag=${tagId}`)
}

// 导航到标签页面
const handleTagNavigate = (tagId) => {
  router.push(`/share?tag=${tagId}`)
}

// 导航到用户主页
const navigateToUserProfile = (userId) => {
  router.push(`/user/${userId}`)
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchComments()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchComments()
}

onMounted(() => {
  fetchShareDetail()
  fetchComments()
  fetchTags()
})
</script>

<style scoped>
.post-detail-card {
  overflow: hidden;
}

.prose {
  font-size: 1.05rem;
  line-height: 1.75;
  color: #374151;
}

.prose p {
  margin-bottom: 1.25em;
}

.prose img {
  max-width: 100%;
  height: auto;
  border-radius: 0.375rem;
}

/* 动画效果 */
@keyframes gradient {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

.animate-gradient {
  background-size: 200% 200%;
  animation: gradient 15s ease infinite;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: transparent;
}

::-webkit-scrollbar-thumb {
  background-color: rgba(156, 163, 175, 0.3);
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background-color: rgba(156, 163, 175, 0.5);
}
</style> 